<template>
  <div>
    <FindView
      @search="handleSearch"
      @reset="handleReset"
      :formItems="[
        {
          type: 'input',
          key: 'searchTitle', // 绑定的字段名（对应后端参数）
          label: '文章标题',
          placeholder: '请输入标题关键词',
          width: '200px',
        },
        {
          type: 'dateRange',
          key: 'publish', // 绑定的字段名
          label: '发布时间',
          startPlaceholder: '开始日期',
          endPlaceholder: '结束日期',
        },
      ]"
      :searchBtn="{ text: '查询文章' }"
    ></FindView>

    <el-button
      type="primary"
      icon="el-icon-edit"
      @click="dialog = true"
      style="margin: 10px 0"
    >
      写文章
    </el-button>

    <el-drawer
      :before-close="handleClose"
      :visible.sync="dialog"
      direction="ttb"
      custom-class="demo-drawer"
      ref="drawer"
      size="100%"
    >
      <div class="demo-drawer__content">
        <div class="title">
          <div><h3>写文章</h3></div>
          <div class="demo-drawer__footer">
            <el-button @click="cancelForm">取 消</el-button>
            <el-button type="primary" @click="submitForm" :loading="loading">
              {{ loading ? "提交中 ..." : "确 定" }}
            </el-button>
          </div>
        </div>
        <el-form :model="form" ref="formRef">
          <el-form-item
            label="标题"
            :label-width="formLabelWidth"
            prop="name"
            :rules="[
              { required: true, message: '请输入标题', trigger: 'blur' },
            ]"
          >
            <el-input
              show-word-limit
              maxlength="40"
              v-model="form.name"
              autocomplete="off"
            ></el-input>
          </el-form-item>
        </el-form>
      </div>
    </el-drawer>

    <el-table :data="list" style="width: 100%" border>
      <el-table-column prop="title" label="文章标题" min-width="200" />
      <el-table-column label="预览图" width="180">
        <template slot-scope="scope">
          <img
            :src="scope.row.titleImage"
            style="width: 60px; height: 45px"
            alt="预览图"
          />
        </template>
      </el-table-column>
      <el-table-column label="发布时间" width="180">
        <template slot-scope="scope">
          <span style="margin-left: 10px">{{ scope.row.createTime }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="180">
        <template slot-scope="scope">
          <el-button size="mini" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button
            size="mini"
            type="danger"
            @click="handleDelete(scope.row)"
            :loading="deleteLoading"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="block" style="margin-top: 20px; text-align: right">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="ruleFrom.current"
        :page-sizes="[10, 20, 50]"
        :page-size="ruleFrom.size"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total.total"
      >
      </el-pagination>
    </div>
  </div>
</template>

<script>
import FindView from "../components/FindView.vue";
export default {
  components: {
    FindView,
  },
  data() {
    return {
      dialog: false,
      loading: false,
      deleteLoading: false,
      list: [],
      total: {
        total: 0,
        pages: 0,
        size: 10,
        current: 1,
      },
      form: {
        name: "",
        id: null,
      },
      formLabelWidth: "80px",
      ruleFrom: {
        current: 1,
        searchTitle: "",
        size: 10,
        startDate: null,
        endDate: null,
      },
    };
  },
  created() {
    this.getlist();
  },
  methods: {
    handleSearch(searchParams) {
      this.ruleFrom = {
        ...this.ruleFrom,
        ...searchParams,
        current: 1,
      };
      this.getlist();
    },

    handleReset() {
      this.ruleFrom = {
        current: 1,
        size: this.ruleFrom.size,
        searchTitle: "",
        startDate: null,
        endDate: null,
      };
      this.getlist();
    },

    handleSizeChange(val) {
      this.ruleFrom.size = val;
      this.ruleFrom.current = 1;
      this.getlist();
    },

    handleCurrentChange(val) {
      this.ruleFrom.current = val;
      this.getlist();
    },

    handleEdit(row) {
      this.dialog = true;
      this.form.name = row.title;
      this.form.id = row.id; 
    },

    handleDelete(row) {
      if (this.deleteLoading) return;

      
      const articleIdValue = row.id;

     
      if (!articleIdValue && articleIdValue !== 0) {
    
        this.$message.error("文章ID不存在，无法删除");
        return;
      }

      this.$confirm(`确定删除《${row.title}》?`, "提示", {
        type: "warning",
      }).then(async () => {
        this.deleteLoading = true;
        try {
        
          const deletePayload = {
            articleId: articleIdValue,
          };

        
          const res = await this.$axios.post(
            "/api/admin/article/delete",
            deletePayload 
          );

          if (res.data.success) {
            this.$message.success("删除成功");
            this.getlist();
          }
        } catch (err) {
          this.$message.error("删除失败：" + err.message);
        } finally {
          this.deleteLoading = false;
        }
      });
    },

    handleClose(done) {
      done();
    },

    cancelForm() {
      this.$refs.formRef.resetFields();
      this.dialog = false;
      this.form.id = null; 
    },

    async submitForm() {
      this.loading = true;
      try {
        await this.$refs.formRef.validate();

        const apiUrl = this.form.id
          ? "/api/admin/article/update"
          : "/api/admin/article/add";

        const res = await this.$axios.post(apiUrl, {
          id: this.form.id, 
          title: this.form.name,
        });

        if (res.data.success || res.data.code === 200) {
          this.$message.success(this.form.id ? "编辑成功" : "新增成功");
          this.dialog = false;
          this.getlist();
          this.$refs.formRef.resetFields();
          this.form.id = null;
        } else {
          this.$message.error(res.data.message || "操作失败");
        }
      } catch (err) {
        if (err.name !== "ValidationError") {
          this.$message.error(err.message || "提交失败");
        }
      } finally {
        this.loading = false;
      }
    },

    async getlist() {
      this.loading = true;
      try {
        const res = await this.$axios.post(
          "/api/admin/article/list",
          this.ruleFrom
        );
        if (res.data.success) {
          this.list = res.data.data.records;
          this.total = res.data.data;
        } else {
          this.$message.error(res.data.message || "获取列表失败");
        }
      } catch (error) {
        this.$message.error(error.message || "网络异常");
      } finally {
        this.loading = false;
      }
    },
  },
};
</script>

<style scoped>
.demo-drawer__content {
  padding: 20px;
  text-align: left;
}
.title {
  width: 100%;
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
  margin-bottom: 20px;
}
img {
  object-fit: cover;
}
</style>